const request = require('supertest');
const pool = require('../../config/db');
const app = require('../../app');

exports.app = app;
exports.request = request;
exports.pool = pool;

// 清理数据库表
exports.clearDatabase = async () => {
  await pool.execute('DELETE FROM order_items');
  await pool.execute('DELETE FROM payments');
  await pool.execute('DELETE FROM orders');
  await pool.execute('DELETE FROM dishes');
  await pool.execute('DELETE FROM combos');
  await pool.execute('DELETE FROM users WHERE username != ?', ['admin']);
};

// 创建测试用户并获取token
// 修改createTestUser函数
exports.createTestUser = async (role = 'user') => {
  const testUser = {
    username: 'testuser' + Math.floor(Math.random() * 1000),
    password: 'testpassword'
  };

  // 注册用户
  const res = await request(app)
    .post('/api/users/register')
    .send(testUser);

  // 检查注册是否成功（不依赖data字段）
  if (res.body.code !== 201) {
    throw new Error(`创建用户失败: ${res.body.msg || '未知错误'}`);
  }

  // 登录获取token
  const loginRes = await request(app)
    .post('/api/users/login')
    .send({
      username: testUser.username,
      password: testUser.password
    });

  // 检查登录是否成功
  if (!loginRes.body.data || !loginRes.body.data.token) {
    throw new Error(`用户登录失败: ${loginRes.body.msg || '未知错误'}`);
  }

  const userId = loginRes.body.data.id;

  // 如果需要管理员角色，更新用户角色
  if (role === 'admin') {
    await pool.query('UPDATE users SET role = ? WHERE id = ?', ['admin', userId]);
  }

  return {
    token: loginRes.body.data.token,
    userId: userId
  };
};

// 创建测试菜品
// 修改createTestDish函数
// 添加创建测试分类的函数
exports.createTestCategory = async (token) => {
  const testCategory = {
    name: '测试分类' + Math.floor(Math.random() * 1000),
    description: '测试分类描述'
  };

  const res = await request(app)
    .post('/api/categories')
    .set('Authorization', `Bearer ${token}`)
    .send(testCategory);

  // 检查响应
  if (res.body.code !== 201 || !res.body.data || !res.body.data.id) {
    throw new Error(`创建分类失败: ${res.body.msg || '未知错误'}`);
  }

  return res.body.data.id;
};

// 修改createTestDish函数，接受categoryId参数
exports.createTestDish = async (token, categoryId) => {
  const testDish = {
    category_id: categoryId,
    name: '测试菜品' + Math.floor(Math.random() * 1000),
    price: 19.99,
    image_url: 'test.jpg',
    description: '测试菜品描述',
    is_spicy: 1,
    inventory: 100,
    status: 1  // 明确设置状态为1
  };

  const res = await request(app)
    .post('/api/dishes')
    .set('Authorization', `Bearer ${token}`)
    .send(testDish);

  // 检查响应
  if (res.body.code !== 201 || !res.body.data || !res.body.data.id) {
    throw new Error(`创建菜品失败: ${res.body.msg || '未知错误'}`);
  }

  return res.body.data.id;
};
// 修改创建测试桌台的函数
exports.createTestTable = async (token) => {
  const testTable = {
    table_number: 'TEST' + Math.floor(Math.random() * 1000),
    status: 0  // 空闲状态
  };

  const res = await request(app)
    .post('/api/tables')
    .set('Authorization', `Bearer ${token}`)
    .send(testTable);

  // 检查响应
  if (res.body.code !== 201 || !res.body.data || !res.body.data.id || !res.body.data.qr_code) {
    throw new Error(`创建桌台失败: ${res.body.msg || '未知错误'}`);
  }

  return {
    id: res.body.data.id,
    qr_code: res.body.data.qr_code
  };
};
